import { getInfoApi, loginApi } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";

const state = {
  token: getToken(), // 读取本地 token
  userInfo: {}, // 用户资料
};

const mutations = {
  // 设置 token
  setToken(state, data) {
    state.token = data; //存vuex
    setToken(data); // 存本地
  },
  // 移除 token
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  // 设置用户资料
  setUserInfo(state, data) {
    state.userInfo = data;
  },
  // 删除用户资料
  removeUserInfo(state) {
    state.userInfo = {};
  },
};

const actions = {
  // 登录的操作
  async loginAction(context, data) {
    const { token, refresh_token } = await loginApi(data);
    // 存储 token
    context.commit("setToken", token);
  },
  // 获取用户资料
  async getUserProfileAction(context) {
    const res = await getInfoApi();
    console.log(res);
    context.commit("setUserInfo", res);
  },
  // 退出操作
  quitAction(context) {
    context.commit("removeToken");
    context.commit("removeUserInfo");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
